<template>
  <div class="customer-contract">
    <gl-breadcrumb class="mb15"
                   text="客户管理,客户详情,注册用户"></gl-breadcrumb>
    <div class="table p20">
      <div class="title">
        <el-button type="primary"
                   @click="showAdd = true">添加合同</el-button>
        <el-button @click="downSome">批量下载</el-button>
      </div>
      <gl-table @button="btnCallback"
                @select="selectChange"
                v-loading="loading"
                class="p20"
                :data="list"
                :columns="listLabel">
        <div slot="doc"
             slot-scope="{row}">
          <span class="el-icon-tickets"
                v-if="row.images.length"></span>
          <span class=""
                v-else>--</span>
        </div>
      </gl-table>
      <gl-pagination :curr="curr"
                     :size="limits"
                     :total="total"
                     @callback="getList"></gl-pagination>
    </div>

    <el-dialog width=""
               title="添加合同"
               :visible.sync="showAdd">
      <gl-form class=""
               ref="addFormRef"
               :must="must"
               :form="addForm"
               :form-label="addFormLabel"
               @upload="uploadSucc">
      </gl-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="showAdd = false">取 消</el-button>
        <el-button type="primary"
                   @click="addContract">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CustomerContract',
  data() {
    return {
      loading: false,
      showAdd: false,

      addForm: {
        images: [
          {
            name: '',
            url: '',
            savepath: ''
          }
        ]
      },
      addFormLabel: [
        { label: '合同编号', prop: 'contract_number', placeholder: '请输入' },
        { label: '合同名称', prop: 'name', placeholder: '请输入' },
        { label: '商务对接人', prop: 'bus_man', placeholder: '请输入' },
        {
          label: '签订时间',
          prop: 'start_time',
          //   dateType: 'date',
          dateType: 'datetime',
          valueFormat: 'timestamp'
        },
        {
          label: '到期时间',
          prop: 'end_time',
          //   dateType: 'date',
          dateType: 'datetime',
          valueFormat: 'timestamp'
        },
        //   {label: '合同', prop: 'images', slot: 'upload'},
        { label: '合同', prop: 'images', type: 'upload', fileList: 'file-list' }
      ],
      must: [],

      list: [],
      selects: [],
      listLabel: [
        { label: '', prop: '', columnType: 'selection' },
        { label: '合同名称', prop: 'contract_name' },
        { label: '合同编号', prop: 'contract_number' },
        { label: '合同文件', slot: 'doc', width: '80px' },
        {
          label: '上传时间',
          prop: 'updatetime',
          format: (val, index, row) => val || row.createtime
        },
        { label: '签订时间', prop: 'start_time' },
        { label: '到期时间', prop: 'end_time' },
        { label: '商务对接人', prop: 'bus_man', width: '100px' },
        // {label: '操作', btns: ['预览', '下载'], width: '100px'},
        { label: '操作', btns: ['下载', '编辑'], width: '100px' }
      ],
      curr: 1,
      limits: 10,
      total: 0,
      tempImgArr: [],
      tempImgsId: ''
    }
  },
  watch: {
    showAdd(val) {
      if (val) {
        if (this.addForm.id) return
        this.addForm = {
          images: [],
          customer_id: this.$route.query.id,
          start_time: '',
          end_time: '',
          contract_number: '',
          name: ''
        }
      } else {
        this.addForm = { images: [] }
        this.$refs.addFormRef.resetFields()
      }
    }
  },
  created() {
    this.getList(1)
    this.must = this.addFormLabel.map(e => e.prop)
  },
  methods: {
    getList(init) {
      if (init) {
        if (init.curr) {
          this.curr = init.curr
          this.limits = init.limits
        } else {
          this.curr = 1
        }
      }
      this.loading = true
      this.http
        .$post('admin/customer.api/customer_contract_list', {
          curr: this.curr,
          limits: this.limits,
          customer_id: this.$route.query.id
        })
        .then(res => {
        //   console.log(res)
          this.loading = false
          this.list = res.list
          this.total = res.total
        })
        .catch(e => {
          this.$err(e)
          this.loading = false
        })
    },
    selectChange(arr, row) {
      this.selects = arr
    },
    uploadSucc(res) {
      //   console.log(res)
      this.addForm.images.push(res)
      //   this.addForm.images.splice(0, this.addForm.images.length, res)
      //   console.log(this.addForm.images)
      // this.$refs.addUploadImg.clear();
    },
    addContract() {
      if (!this.$refs.addFormRef.validate()) return
      let url = 'admin2/customer.api/customer_contract_add'
      this.addForm.id && (url = 'admin/customer.api/customer_contract_update')
      this.http
        .$post(url, {
          ...this.addForm,
          start_time: (this.addForm.start_time / 1000) | 0,
          end_time: (this.addForm.end_time / 1000) | 0,
          images: this.addForm.images.map(e => e.savepath).filter(e => e)
        })
        .then(res => {
          this.$message.success('添加成功')
          this.showAdd = false
          this.getList()
        })
        .catch(this.$err)
    },
    downSome() {
      let list = []
      if (!this.selects.length) {
        this.$message('请至少选择一个合同')
        return
      }
      this.selects.map(row => {
        list.push(...row.all_images)
      })
      this.btnCallback({
        index: 0,
        row: {
          all_images: list,
          contract_number:
            'contract_' + this.tools.formatDate(new Date(), 'Y-M-D')
        }
      })
    },
    btnCallback({ row, index }) {
      if (index === 0) {
        // 下载
        let loading = this.$loading()
        if (row.all_images.length > 1) {
          this.tools
            .zipDownload(
              row.contract_number,
              row.all_images,
              row.all_images.map(
                (e, i) =>
                  e
                    .split('=')
                    .pop()
                    .split('.')[0] +
                  '_' +
                  (i + 1) +
                  '.' +
                  e.split('.').pop()
              )
            )
            .then(r => {
              loading.close()
              this.tools.download(row.contract_number, r)
            })
            .catch(e => {
              loading.close()
              console.log(e)
            })
        } else {
          row.all_images.map(e => {
            this.tools.download('', e)
          })
          loading.close()
        }
      } else {
        row = { ...row }
        row.images = JSON.parse(JSON.stringify(row)).all_images.map((e, i) => ({
          name: i,
          url: e,
          file_path: e,
          savepath: row.images[i]
        }))
        row.start_time = new Date(row.start_time)
        row.end_time = new Date(row.end_time)
        row.name = row.contract_name
        this.addForm = row
        this.showAdd = true

        return
      }
    }
  }
}
</script>

<style scoped lang="less">
.table {
  background-color: #fff;
}

.upload-box {
  .gl-update {
    width: 100px;
    height: 100px;
  }
  .el-icon-close {
    padding: 0;
    font-weight: bold;
  }
  .upload-button {
    padding-top: 0;
    padding-bottom: 0;
    line-height: 30px;
    height: 30px;
  }
}
</style>